package com.salary.utils.reader;

import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UtilityRentDataReader extends DataReader<Map<String, Double>>{
    private static final Logger logger = LoggerFactory.getLogger(UtilityRentDataReader.class);

    /**
     * 从水电租表读取水电房租数据
     */
    @Override
    public Map<String, Double> readData(String filePath) {
        Map<String, Double> utilityRentData = new HashMap<>();

        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = WorkbookFactory.create(fis)) {

            // 获取"数据源"工作表
            Sheet sheet = workbook.getSheet("数据源");
            if (sheet == null) {
                logger.error("水电租表中未找到名为'数据源'的工作表");
                return utilityRentData;
            }

            logger.info("从水电租表的'数据源'工作表读取数据");

            // 使用通用方法查找列
            Map<String, Integer> columnIndices = findColumnIndices(sheet, new String[]{"姓名", "租金","水费", "热水费","电费", "合计"});

            // 验证是否找到必要的列
            if (!columnIndices.containsKey("姓名") || !columnIndices.containsKey("租金")
                    || !columnIndices.containsKey("水费")|| !columnIndices.containsKey("热水费")
                    || !columnIndices.containsKey("电费")|| !columnIndices.containsKey("合计")) {
                logger.error("水电租表中未找到必要的列");
                return utilityRentData;
            }

            int nameColIndex = columnIndices.get("姓名");
            int totalColIndex = columnIndices.get("合计");


            // 从第二行开始读取数据（跳过表头）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                Cell nameCell = row.getCell(nameColIndex);
                if (nameCell == null) continue;

                String name = getCellValueAsString(nameCell).trim();
                if (name.isEmpty()) continue;

                double total = 0;

                // 如果有合计列，优先使用合计列的值
                if (totalColIndex != -1) {
                    Cell totalCell = row.getCell(totalColIndex);
                    if (totalCell != null) {
                        total = getCellValueAsDouble(totalCell);
                    }
                }


                // 只有当金额不为0时才添加记录
                if (total != 0) {
                    utilityRentData.put(name, total);
                    logger.info("读取到水电房租数据: " + name + " - " + total);
                }
            }

            logger.info("成功从水电租表读取了 " + utilityRentData.size() + " 条记录");

        } catch (IOException e) {
            logger.error("读取水电租表文件失败: " + e.getMessage(), e);
        }

        return utilityRentData;
    }
}
